In this project, you will apply unsupervised learning techniques to identify segments of the population that form the core customer base for a mail-order sales company in Germany. These segments can then be used to direct marketing campaigns towards audiences that will have the highest expected rate of returns. The data that you will use has been provided by our partners at Bertelsmann Arvato Analytics, and represents a real-life data science task.
This notebook will help you complete this task by providing a framework within which you will perform your analysis steps. In each step of the project, you will see some text describing the subtask that you will perform, followed by one or more code cells for you to complete your work. Feel free to add additional code and markdown cells as you go along so that you can explore everything in precise chunks. The code cells provided in the base template will outline only the major tasks, and will usually not be enough to cover all of the minor tasks that comprise it.
It should be noted that while there will be precise guidelines on how you should handle certain tasks in the project, there will also be places where an exact specification is not provided. There will be times in the project where you will need to make and justify your own decisions on how to treat the data. These are places where there may not be only one way to handle the data. In real-life tasks, there may be many valid ways to approach an analysis task. One of the most important things you can do is clearly document your approach so that other scientists can understand the decisions you've made.
At the end of most sections, there will be a Markdown cell labeled Discussion. In these cells, you will report your findings for the completed section, as well as document the decisions that you made in your approach to each subtask. Your project will be evaluated not just on the code used to complete the tasks outlined, but also your communication about your observations and conclusions at each stage.
# import libraries here; add more as necessary
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import Imputer
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from collections import Counter
# magic word for producing visualizations in notebook
%matplotlib inline
'''
Import note: The classroom currently uses sklearn version 0.19.
If you need to use an imputer, it is available in sklearn.preprocessing.Imputer,
instead of sklearn.impute as in newer versions of sklearn.
'''
There are four files associated with this project (not including this one):
Udacity_AZDIAS_Subset.csv: Demographics data for the general population of Germany; 891211 persons (rows) x 85 features (columns).Udacity_CUSTOMERS_Subset.csv: Demographics data for customers of a mail-order company; 191652 persons (rows) x 85 features (columns).Data_Dictionary.md: Detailed information file about the features in the provided datasets.AZDIAS_Feature_Summary.csv: Summary of feature attributes for demographics data; 85 features (rows) x 4 columnsEach row of the demographics files represents a single person, but also includes information outside of individuals, including information about their household, building, and neighborhood. You will use this information to cluster the general population into groups with similar demographic properties. Then, you will see how the people in the customers dataset fit into those created clusters. The hope here is that certain clusters are over-represented in the customers data, as compared to the general population; those over-represented clusters will be assumed to be part of the core userbase. This information can then be used for further applications, such as targeting for a marketing campaign.
To start off with, load in the demographics data for the general population into a pandas DataFrame, and do the same for the feature attributes summary. Note for all of the .csv data files in this project: they're semicolon (;) delimited, so you'll need an additional argument in your read_csv() call to read in the data properly. Also, considering the size of the main dataset, it may take some time for it to load completely.
Once the dataset is loaded, it's recommended that you take a little bit of time just browsing the general structure of the dataset and feature summary file. You'll be getting deep into the innards of the cleaning in the first major step of the project, so gaining some general familiarity can help you get your bearings.
# Load in the general demographics data.
azdias = pd.DataFrame(pd.read_csv('./Udacity_AZDIAS_Subset.csv', delimiter = ';'))
# Load in the feature summary file.
feat_info = pd.DataFrame(pd.read_csv('./AZDIAS_Feature_Summary.csv', delimiter = ';'))
# Check the structure of the data after it's loaded (e.g. print the number of
# rows and columns, print the first few rows).
azdias.head()
azdias.shape
azdias.info()
feat_info.head()
# To explore the summaries of Azdias dataset
azdias.describe()
# To see the correlation of each pair of features
plt.figure(figsize=(144,120))
cor = azdias.corr()
sns.heatmap(cor, annot=True, cmap=plt.cm.Reds)
plt.show()
Tip: Add additional cells to keep everything in reasonably-sized chunks! Keyboard shortcut
esc --> a(press escape to enter command mode, then press the 'A' key) adds a new cell before the active cell, andesc --> badds a new cell after the active cell. If you need to convert an active cell to a markdown cell, useesc --> mand to convert to a code cell, useesc --> y.
The feature summary file contains a summary of properties for each demographics data column. You will use this file to help you make cleaning decisions during this stage of the project. First of all, you should assess the demographics data in terms of missing data. Pay attention to the following points as you perform your analysis, and take notes on what you observe. Make sure that you fill in the Discussion cell with your findings and decisions at the end of each step that has one!
The fourth column of the feature attributes summary (loaded in above as feat_info) documents the codes from the data dictionary that indicate missing or unknown data. While the file encodes this as a list (e.g. [-1,0]), this will get read in as a string object. You'll need to do a little bit of parsing to make use of it to identify and clean the data. Convert data that matches a 'missing' or 'unknown' value code into a numpy NaN value. You might want to see how much data takes on a 'missing' or 'unknown' code, and how much data is naturally missing, as a point of interest.
As one more reminder, you are encouraged to add additional cells to break up your analysis into manageable chunks.
azdias.isnull().sum()
azdias.isnull().sum().sum()
azdias_1 = azdias.copy()
# Identify missing or unknown data values and convert them to NaNs.
for i in range(len(feat_info)):
mssng = feat_info['missing_or_unknown'][i].strip('[').strip(']').split(',')
mssng = [int(value) if (value!='X' and value!='XX' and value!='') else value for value in mssng]
if mssng != ['']:
azdias_1 = azdias_1.replace({feat_info.iloc[i].attribute: mssng}, np.nan)
azdias.isnull().sum().sum()
azdias_1.isnull().sum().sum()
How much missing data is present in each column? There are a few columns that are outliers in terms of the proportion of values that are missing. You will want to use matplotlib's hist() function to visualize the distribution of missing value counts to find these columns. Identify and document these columns. While some of these columns might have justifications for keeping or re-encoding the data, for this project you should just remove them from the dataframe. (Feel free to make remarks about these outlier columns in the discussion, however!)
For the remaining features, are there any patterns in which columns have, or share, missing data?
azdias_1_isnull = azdias_1.isnull().sum().sort_values(ascending = False)
for i in azdias_1_isnull:
print(i, i/len(azdias)*100)
# Perform an assessment of how much missing data there is in each column of the
# dataset.
azdias_1.isnull().sum().sort_values(ascending = False)
# Remove the outlier columns from the dataset. (You'll perform other data
# engineering tasks such as re-encoding and imputation later.)
azdias_1.drop(['TITEL_KZ', 'AGER_TYP', 'KK_KUNDENTYP', 'KBA05_BAUMAX'], axis = 1, inplace = True)
azdias_1.head()
(Double click this cell and replace this text with your own text, reporting your observations regarding the amount of missing data in each column. Are there any patterns in missing values? Which columns were removed from the dataset?)
The AZDIAS dataset has a total of 8,373,929 NaN values out of 891,221 x 85 values. We observed that the top features that has more than 50% of its values as NaN values are TITEL_KZ, AGER_TYP, KK_KUNDENTYP, and KBA05_BAUMAX. We dropped these feature columns from our dataset AZDIAS.
Now, you'll perform a similar assessment for the rows of the dataset. How much data is missing in each row? As with the columns, you should see some groups of points that have a very different numbers of missing values. Divide the data into two subsets: one for data points that are above some threshold for missing values, and a second subset for points below that threshold.
In order to know what to do with the outlier rows, we should see if the distribution of data values on columns that are not missing data (or are missing very little data) are similar or different between the two groups. Select at least five of these columns and compare the distribution of values.
countplot() function to create a bar chart of code frequencies and matplotlib's subplot() function to put bar charts for the two subplots side by side.Depending on what you observe in your comparison, this will have implications on how you approach your conclusions later in the analysis. If the distributions of non-missing features look similar between the data with many missing values and the data with few or no missing values, then we could argue that simply dropping those points from the analysis won't present a major issue. On the other hand, if the data with many missing values looks very different from the data with few or no missing values, then we should make a note on those data as special. We'll revisit these data later on. Either way, you should continue your analysis for now using just the subset of the data with few or no missing values.
azdias_2 = azdias_1.copy()
azdias_2_more_20 = azdias_2[azdias_2.isnull().sum(axis = 1) >= 20]
azdias_2_less_20 = azdias_2[azdias_2.isnull().sum(axis = 1) < 20]
print(azdias_2_more_20.shape)
print(azdias_2_less_20.shape)
print(azdias_2.shape)
azdias_2_more_20.head()
azdias_2 = azdias_2_less_20
# Compare the distribution of values for at least five columns where there are
# no or few missing values, between the two subsets.
sns.distplot(azdias_2['ALTERSKATEGORIE_GROB'].notnull());
sns.distplot(azdias_2_more_20['ALTERSKATEGORIE_GROB'].notnull());
sns.distplot(azdias_2_less_20['ALTERSKATEGORIE_GROB'].notnull());
sns.distplot(azdias_2['CJT_GESAMTTYP'].notnull());
sns.distplot(azdias_2_more_20['CJT_GESAMTTYP'].notnull());
sns.distplot(azdias_2_less_20['CJT_GESAMTTYP'].notnull());
sns.distplot(azdias_3['ARBEIT'].notnull());
sns.distplot(azdias_3_more_20['ARBEIT'].notnull());
sns.distplot(azdias_2_less_20['ARBEIT'].notnull());
(Double-click this cell and replace this text with your own text, reporting your observations regarding missing data in rows. Are the data with lots of missing values are qualitatively different from data with few or no missing values?)
I have chosen to drop the row that has more than 20 NaN values. When I checked the distribution for ALTERSKATEGORIE_GROB, CJT_GESAMTTYP and ARBEIT features, I found that for the first two there is no difference in distributions, but for the latter, there is a difference.
Checking for missing data isn't the only way in which you can prepare a dataset for analysis. Since the unsupervised learning techniques to be used will only work on data that is encoded numerically, you need to make a few encoding changes or additional assumptions to be able to make progress. In addition, while almost all of the values in the dataset are encoded using numbers, not all of them represent numeric values. Check the third column of the feature summary (feat_info) for a summary of types of measurement.
In the first two parts of this sub-step, you will perform an investigation of the categorical and mixed-type features and make a decision on each of them, whether you will keep, drop, or re-encode each. Then, in the last part, you will create a new data frame with only the selected and engineered columns.
Data wrangling is often the trickiest part of the data analysis process, and there's a lot of it to be done here. But stick with it: once you're done with this step, you'll be ready to get to the machine learning parts of the project!
azdias_3 = azdias_2.copy()
azdias_3['OST_WEST_KZ'] = azdias_3['OST_WEST_KZ'].map({'W': 1, 'O': 0})
azdias_3['CAMEO_DEU_2015'] = azdias_3['CAMEO_DEU_2015'].map({'1A': 1, '1B': 2, '1C': 3, '1D': 4, '1E': 5,
'2A': 6, '2B': 7, '2C': 8, '2D': 9,
'3A': 10, '3B': 11, '3C': 12, '3D': 13,
'4A': 14, '4B': 15, '4C': 16, '4D': 17, '4E': 18,
'5A': 19, '5B': 20, '5C': 21, '5D': 22, '5E': 23, '5F': 24,
'6A': 25, '6B': 26, '6C': 27, '6D': 28, '6E': 29, '6F': 30,
'7A': 31, '7B': 32, '7C': 33, '7D': 34, '7E': 35,
'8A': 36, '8B': 37, '8C': 38, '8D': 39,
'9A': 40, '9B': 41, '9C': 42, '9D': 43, '9E': 44})
azdias_3.shape
azdias.isnull().sum().sum()
azdias_2.isnull().sum().sum()
azdias_3.isnull().sum().sum()
azdias_3.head(2)
azdias_4 = azdias_3.copy()
azdias_4_head = azdias_4.columns
azdias_4_head
imputer = Imputer(missing_values = np.nan, strategy = 'most_frequent', axis = 0)
azdias_4 = imputer.fit_transform(azdias_4)
azdias_4 = pd.DataFrame(azdias_4, columns = azdias_4_head)
azdias_4.shape
azdias_4.head(2)
azdias_4.isnull().sum().sum()
azdias_4.info()
For categorical data, you would ordinarily need to encode the levels as dummy variables. Depending on the number of categories, perform one of the following:
# Done in the previous cells
(Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding categorical features. Which ones did you keep, which did you drop, and what engineering steps did you perform?)
Features 'OST_WEST_KZ' and 'CAMEO_DEU_2015' have been encoded. Missing values have been imputed with the most frequent value (the mode)
There are a handful of features that are marked as "mixed" in the feature summary that require special treatment in order to be included in the analysis. There are two in particular that deserve attention; the handling of the rest are up to your own choices:
Be sure to check Data_Dictionary.md for the details needed to finish these tasks.
azdias_5 = azdias_4.copy()
# Investigate "PRAEGENDE_JUGENDJAHRE" and engineer two new variables.
azdias_5.PRAEGENDE_JUGENDJAHRE.value_counts()
# Investigate "CAMEO_INTL_2015" and engineer two new variables.
azdias_5.CAMEO_INTL_2015.value_counts()
decade_dict = {1:1, 2:1, 3:2, 4:2, 5:3, 6:3, 7:3, 8:4, 9:4, 10:5, 11:5, 12:5, 13:5, 14:6, 15:6}
movement_dict = {1:1 , 2:0 , 3:1 , 4:0 , 5:1 , 6:0 , 7:0 , 8:1 , 9:0 , 10:1 , 11:0 , 12:1 , 13:0 , 14:1 , 15:0}
azdias_5['DECADE'] = azdias_5['PRAEGENDE_JUGENDJAHRE']
azdias_5['MOVEMENT'] = azdias_5['PRAEGENDE_JUGENDJAHRE']
azdias_5["DECADE"].replace(decade_dict, inplace = True)
azdias_5['MOVEMENT'].replace(movement_dict, inplace = True)
azdias_5.info()
azdias_5.drop(['PRAEGENDE_JUGENDJAHRE'], axis = 1, inplace = True)
azdias_5.info()
new_dict = {11:1, 12:1, 13:1, 14:1, 15:1, 21:2, 22:2, 23:2, 24:2, 25:2, 31:3, 32:3, 33:3, 34:3, 35:3, 41:4, 42:4, 43:4, 44:4, 45:4, 51:5, 52:5, 53:5, 54:5, 55:5}
azdias_5['CAMEO_INTL_2015_NEW'] = azdias_5['CAMEO_INTL_2015']
azdias_5["CAMEO_INTL_2015_NEW"].replace(new_dict, inplace = True)
azdias_5.drop(['CAMEO_INTL_2015'], axis = 1, inplace = True)
azdias_5.info()
(Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding mixed-value features. Which ones did you keep, which did you drop, and what engineering steps did you perform?)
Features 'PRAEGENDE_JUGENDJAHRE' and 'CAMEO_INTL_2015' have been re-engineered because they previously had too many variables that can be grouped to facilitate the analysis and training the model
In order to finish this step up, you need to make sure that your data frame now only has the columns that you want to keep. To summarize, the dataframe should consist of the following:
Make sure that for any new columns that you have engineered, that you've excluded the original columns from the final dataset. Otherwise, their values will interfere with the analysis later on the project. For example, you should not keep "PRAEGENDE_JUGENDJAHRE", since its values won't be useful for the algorithm: only the values derived from it in the engineered features you created should be retained. As a reminder, your data should only be from the subset with few or no missing values.
features = list(azdias_5.columns)
feat_info_1 = feat_info[feat_info['attribute'].isin(features)]
mixed_features = feat_info_1[feat_info_1["type"] == "mixed"]["attribute"]
for feature in mixed_features:
azdias_5.drop(feature, axis = 1, inplace = True)
azdias_5.isnull().sum().sum()
azdias_5.head(2)
Even though you've finished cleaning up the general population demographics data, it's important to look ahead to the future and realize that you'll need to perform the same cleaning steps on the customer demographics data. In this substep, complete the function below to execute the main feature selection, encoding, and re-engineering steps you performed above. Then, when it comes to looking at the customer data in Step 3, you can just run this function on that DataFrame to get the trimmed dataset in a single step.
def clean_data(df):
"""
Perform feature trimming, re-encoding, and engineering for demographics
data
INPUT: Demographics DataFrame
OUTPUT: Trimmed and cleaned demographics DataFrame
"""
df_1 = df.copy()
for i in range(len(feat_info)):
mssng = feat_info['missing_or_unknown'][i].strip('[').strip(']').split(',')
mssng = [int(value) if (value!='X' and value!='XX' and value!='') else value for value in mssng]
if mssng != ['']:
df_1 = df_1.replace({feat_info.iloc[i].attribute: mssng}, np.nan)
df_1.drop(['TITEL_KZ', 'AGER_TYP', 'KK_KUNDENTYP', 'KBA05_BAUMAX'], axis = 1, inplace = True)
df_2 = df_1.copy()
df_2[df_2.isnull().sum(axis = 1) < 20]
df_3 = df_2.copy()
df_3['OST_WEST_KZ'] = df_3['OST_WEST_KZ'].map({'W': 1, 'O': 0})
df_3['CAMEO_DEU_2015'] = df_3['CAMEO_DEU_2015'].map({'1A': 1, '1B': 2, '1C': 3, '1D': 4, '1E': 5,
'2A': 6, '2B': 7, '2C': 8, '2D': 9,
'3A': 10, '3B': 11, '3C': 12, '3D': 13,
'4A': 14, '4B': 15, '4C': 16, '4D': 17, '4E': 18,
'5A': 19, '5B': 20, '5C': 21, '5D': 22, '5E': 23, '5F': 24,
'6A': 25, '6B': 26, '6C': 27, '6D': 28, '6E': 29, '6F': 30,
'7A': 31, '7B': 32, '7C': 33, '7D': 34, '7E': 35,
'8A': 36, '8B': 37, '8C': 38, '8D': 39,
'9A': 40, '9B': 41, '9C': 42, '9D': 43, '9E': 44})
df_4 = df_3.copy()
df_4_head = df_4.columns
imputer = Imputer(missing_values = np.nan, strategy = 'most_frequent', axis = 0)
df_4 = imputer.fit_transform(df_4)
df_4 = pd.DataFrame(df_4, columns = df_4_head)
df_5 = df_4.copy()
decade_dict = {1:1, 2:1, 3:2, 4:2, 5:3, 6:3, 7:3, 8:4, 9:4, 10:5, 11:5, 12:5, 13:5, 14:6, 15:6}
movement_dict = {1:1 , 2:0 , 3:1 , 4:0 , 5:1 , 6:0 , 7:0 , 8:1 , 9:0 , 10:1 , 11:0 , 12:1 , 13:0 , 14:1 , 15:0}
df_5['DECADE'] = df_5['PRAEGENDE_JUGENDJAHRE']
df_5['MOVEMENT'] = df_5['PRAEGENDE_JUGENDJAHRE']
df_5["DECADE"].replace(decade_dict, inplace = True)
df_5['MOVEMENT'].replace(movement_dict, inplace = True)
new_dict = {11:1, 12:1, 13:1, 14:1, 15:1, 21:2, 22:2, 23:2, 24:2, 25:2, 31:3, 32:3, 33:3, 34:3, 35:3, 41:4, 42:4, 43:4, 44:4, 45:4, 51:5, 52:5, 53:5, 54:5, 55:5}
df_5['CAMEO_INTL_2015_NEW'] = df_5['CAMEO_INTL_2015']
df_5["CAMEO_INTL_2015_NEW"].replace(new_dict, inplace = True)
df_5 = df_5.drop(['PRAEGENDE_JUGENDJAHRE', 'CAMEO_INTL_2015'], axis = 1, inplace = True)
features = list(df_5.columns)
feat_info_1 = feat_info[feat_info['attribute'].isin(features)]
mixed_features = feat_info_1[feat_info_1["type"] == "mixed"]["attribute"]
for feature in mixed_features:
df_5.drop(feature, axis = 1, inplace = True)
return df_5
azdias_6 = azdias.copy()
clean_data(azdias_6)
azdias_5.head(2)
azdias_6.head(2)
Before we apply dimensionality reduction techniques to the data, we need to perform feature scaling so that the principal component vectors are not influenced by the natural differences in scale for features. Starting from this part of the project, you'll want to keep an eye on the API reference page for sklearn to help you navigate to all of the classes and functions that you'll need. In this substep, you'll need to check the following:
.fit_transform() method to both fit a procedure to the data as well as apply the transformation to the data at the same time. Don't forget to keep the fit sklearn objects handy, since you'll be applying them to the customer demographics data towards the end of the project.azdias_7 = azdias_5.copy()
azdias_7_head = azdias_7.columns
# If you've not yet cleaned the dataset of all NaN values, then investigate and
# do that now.
scaler = StandardScaler()
azdias_7 = scaler.fit_transform(azdias_7)
azdias_7 = pd.DataFrame(azdias_7, columns = azdias_7_head)
azdias_7.head(2)
(Double-click this cell and replace this text with your own text, reporting your decisions regarding feature scaling.)
All features were standardized using StandardScaler tool.
On your scaled data, you are now ready to apply dimensionality reduction techniques.
plot() function. Based on what you find, select a value for the number of transformed features you'll retain for the clustering part of the project.pca = PCA(n_components = 78)
pca.fit(azdias_7)
# Apply PCA to the data.
def screen_plot(pca):
n_components = len(pca.explained_variance_ratio_)
index = np.arange(n_components)
values = pca.explained_variance_ratio_
plt.figure(figsize = (20, 10))
ax = plt.subplot(111)
cumvals = np.cumsum(values)
ax.bar(index, values)
ax.plot(index, cumvals)
for i in range(n_components):
ax.annotate(r"%s%%" % ((str(values[i]*100)[:4])), (index[i]+0.2, values[i]), va = 'bottom', ha = 'center', fontsize = 12)
ax.xaxis.set_tick_params(width = 0)
ax.yaxis.set_tick_params(width = 2, length = 12)
ax.set_xlabel('Principal Component')
ax.set_ylabel('Variance Explained (%)')
plt.title('Explained Variance Per Principal Component')
# Investigate the variance accounted for by each principal component.
screen_plot(pca)
# Re-apply PCA to the data while selecting for number of components to retain.
pca = PCA(n_components = 14)
pca.fit(azdias_7)
pca.transform(azdias_7)
screen_plot(pca)
(Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding dimensionality reduction. How many principal components / transformed features are you retaining for the next step of the analysis?)
Now that we have our transformed principal components, it's a nice idea to check out the weight of each variable on the first few components to see if they can be interpreted in some fashion.
As a reminder, each principal component is a unit vector that points in the direction of highest variance (after accounting for the variance captured by earlier principal components). The further a weight is from zero, the more the principal component is in the direction of the corresponding feature. If two features have large weights of the same sign (both positive or both negative), then increases in one tend expect to be associated with increases in the other. To contrast, features with different signs can be expected to show a negative correlation: increases in one variable should result in a decrease in the other.
# Map weights for the first principal component to corresponding feature names
# and then print the linked values, sorted by weight.
# HINT: Try defining a function here or in a new cell that you can reuse in the
# other cells.
def pca_results(good_data, pca):
dimensions = dimensions = ['Dimension {}'.format(i) for i in range(1,len(pca.components_)+1)]
components = pd.DataFrame(np.round(pca.components_, 4), columns = list(good_data.keys()))
components.index = dimensions
ratios = pca.explained_variance_ratio_.reshape(len(pca.components_), 1)
variance_ratios = pd.DataFrame(np.round(ratios, 4), columns = ['Explained Variance'])
variance_ratios.index = dimensions
fig, ax = plt.subplots(figsize = (14,8))
components.plot(ax = ax, kind = 'bar');
ax.set_ylabel("Feature Weights")
ax.set_xticklabels(dimensions, rotation=0)
for i, ev in enumerate(pca.explained_variance_ratio_):
ax.text(i-0.40, ax.get_ylim()[1] + 0.05, "Explained Variance\n%.4f"%(ev))
return pd.concat([variance_ratios, components], axis = 1)
pca_results(azdias_7, pca)
# Map weights for the second principal component to corresponding feature names
# and then print the linked values, sorted by weight.
# Map weights for the third principal component to corresponding feature names
# and then print the linked values, sorted by weight.
(Double-click this cell and replace this text with your own text, reporting your observations from detailed investigation of the first few principal components generated. Can we interpret positive and negative values from them in a meaningful way?)
PCA has been performed over cleaned azdias dataset (azdias_7). Then we have taken the major 14 components as these components has variance expalianed more than 60%.
You've assessed and cleaned the demographics data, then scaled and transformed them. Now, it's time to see how the data clusters in the principal components space. In this substep, you will apply k-means clustering to the dataset and use the average within-cluster distances from each point to their assigned cluster's centroid to decide on a number of clusters to keep.
.score() method might be useful here, but note that in sklearn, scores tend to be defined so that larger is better. Try applying it to a small, toy dataset, or use an internet search to help your understanding.def get_kmeans_score(data, center):
'''
returns the kmeans score regarding SSE for points to centers
INPUT:
data - the dataset you want to fit kmeans to
center - the number of centers you want (the k value)
OUTPUT:
score - the SSE score for the kmeans model fit to the data
'''
#instantiate kmeans
kmeans = KMeans(n_clusters=center)
# Then fit the model to your data using the fit method
model = kmeans.fit(data)
# Obtain a score related to the model fit
score = np.abs(model.score(data))
return score
scores = []
centers = list(range(1,15))
for center in centers:
scores.append(get_kmeans_score(azdias_7, center))
plt.plot(centers, scores, linestyle='--', marker='o', color='b');
plt.xlabel('K');
plt.ylabel('SSE');
plt.title('SSE vs. K');
azdias_7 = pca.transform(azdias_7)
kmeans = KMeans(n_clusters = 4)
model = kmeans.fit(azdias_7)
labels_azdias = model.predict(azdias_7)
labels_azdias
plt.scatter(azdias_7[:,0], azdias_7[:,1], c = labels_azdias, cmap = 'Set1');
# Over a number of different cluster counts...
# run k-means clustering on the data and...
# compute the average within-cluster distances.
# Investigate the change in within-cluster distance across number of clusters.
# HINT: Use matplotlib's plot function to visualize this relationship.
# Re-fit the k-means model with the selected number of clusters and obtain
# cluster predictions for the general population demographics data.
(Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding clustering. Into how many clusters have you decided to segment the population?)
As seen in the elbow diagram, it seems that 4 clusters is the perfect choice. We've chosen to apply k-means over the principal components of azdias_7 with 4 clusters.
Now that you have clusters and cluster centers for the general population, it's time to see how the customer data maps on to those clusters. Take care to not confuse this for re-fitting all of the models to the customer data. Instead, you're going to use the fits from the general population to clean, transform, and cluster the customer data. In the last step of the project, you will interpret how the general population fits apply to the customer data.
;) delimited.clean_data() function you created earlier. (You can assume that the customer demographics data has similar meaning behind missing data patterns as the general demographics data.).fit() or .fit_transform() method to re-fit the old objects, nor should you be creating new sklearn objects! Carry the data through the feature scaling, PCA, and clustering steps, obtaining cluster assignments for all of the data in the customer demographics data.# Load in the customer demographics data.
customers = pd.DataFrame(pd.read_csv('./Udacity_CUSTOMERS_Subset.csv', delimiter = ';'))
customers_1 = customers.copy()
customers_1.info()
# Apply preprocessing, feature transformation, and clustering from the general
# demographics onto the customer data, obtaining cluster predictions for the
# customer demographics data.
customers_2 = clean_data(customers_1)
customers_2.isnull().sum().sum()
customers_3 = customers.copy()
customers_3.isnull().sum().sum()
for i in range(len(feat_info)):
mssng_1 = feat_info['missing_or_unknown'][i].strip('[').strip(']').split(',')
mssng_1 = [int(value) if (value!='X' and value!='XX' and value!='') else value for value in mssng_1]
if mssng != ['']:
customers_3 = customers_3.replace({feat_info.iloc[i].attribute: mssng_1}, np.nan)
customers_3.drop(['TITEL_KZ', 'AGER_TYP', 'KK_KUNDENTYP', 'KBA05_BAUMAX'], axis = 1, inplace = True)
customers_4 = customers_3.copy()
customers_4[customers_4.isnull().sum(axis = 1) < 20]
customers_5 = customers_4.copy()
customers_5['OST_WEST_KZ'] = customers_5['OST_WEST_KZ'].map({'W': 1, 'O': 0})
customers_5['CAMEO_DEU_2015'] = customers_5['CAMEO_DEU_2015'].map({'1A': 1, '1B': 2, '1C': 3, '1D': 4, '1E': 5,
'2A': 6, '2B': 7, '2C': 8, '2D': 9,
'3A': 10, '3B': 11, '3C': 12, '3D': 13,
'4A': 14, '4B': 15, '4C': 16, '4D': 17, '4E': 18,
'5A': 19, '5B': 20, '5C': 21, '5D': 22, '5E': 23, '5F': 24,
'6A': 25, '6B': 26, '6C': 27, '6D': 28, '6E': 29, '6F': 30,
'7A': 31, '7B': 32, '7C': 33, '7D': 34, '7E': 35,
'8A': 36, '8B': 37, '8C': 38, '8D': 39,
'9A': 40, '9B': 41, '9C': 42, '9D': 43, '9E': 44})
customers_6 = customers_5.copy()
customers_6_head = customers_6.columns
imputer = Imputer(missing_values = np.nan, strategy = 'most_frequent', axis = 0)
customers_6 = imputer.fit_transform(customers_6)
customers_6 = pd.DataFrame(customers_6, columns = customers_6_head)
customers_7 = customers_6.copy()
decade_dict = {1:1, 2:1, 3:2, 4:2, 5:3, 6:3, 7:3, 8:4, 9:4, 10:5, 11:5, 12:5, 13:5, 14:6, 15:6}
movement_dict = {1:1 , 2:0 , 3:1 , 4:0 , 5:1 , 6:0 , 7:0 , 8:1 , 9:0 , 10:1 , 11:0 , 12:1 , 13:0 , 14:1 , 15:0}
customers_7['DECADE'] = customers_7['PRAEGENDE_JUGENDJAHRE']
customers_7['MOVEMENT'] = customers_7['PRAEGENDE_JUGENDJAHRE']
customers_7["DECADE"].replace(decade_dict, inplace = True)
customers_7['MOVEMENT'].replace(movement_dict, inplace = True)
new_dict = {11:1, 12:1, 13:1, 14:1, 15:1, 21:2, 22:2, 23:2, 24:2, 25:2, 31:3, 32:3, 33:3, 34:3, 35:3, 41:4, 42:4, 43:4, 44:4, 45:4, 51:5, 52:5, 53:5, 54:5, 55:5}
customers_7['CAMEO_INTL_2015_NEW'] = customers_7['CAMEO_INTL_2015']
customers_7["CAMEO_INTL_2015_NEW"].replace(new_dict, inplace = True)
customer_7 = customers_7.drop(['PRAEGENDE_JUGENDJAHRE', 'CAMEO_INTL_2015'], axis = 1, inplace = True)
features = list(customers_7.columns)
feat_info_1 = feat_info[feat_info['attribute'].isin(features)]
mixed_features = feat_info_1[feat_info_1["type"] == "mixed"]["attribute"]
for feature in mixed_features:
customers_7.drop(feature, axis = 1, inplace = True)
customers_7.isnull().sum().sum()
customers_7.head(2)
customers_8 = customers_7.copy()
customers_8_head = customers_8.columns
scaler_1 = StandardScaler()
customers_8 = scaler_1.fit_transform(customers_8)
customers_8 = pd.DataFrame(customers_8, columns = customers_8_head)
customers_9 = customers_8.copy()
customers_9 = pca.transform(customers_9)
screen_plot(pca)
kmeans = KMeans(n_clusters = 4)
model = kmeans.fit(customers_9)
labels_customers = model.predict(customers_9)
plt.scatter(customers_9[:,0], customers_9[:,1], c = labels, cmap = 'Set1');
At this point, you have clustered data based on demographics of the general population of Germany, and seen how the customer data for a mail-order sales company maps onto those demographic clusters. In this final substep, you will compare the two cluster distributions to see where the strongest customer base for the company is.
Consider the proportion of persons in each cluster for the general population, and the proportions for the customers. If we think the company's customer base to be universal, then the cluster assignment proportions should be fairly similar between the two. If there are only particular segments of the population that are interested in the company's products, then we should see a mismatch from one to the other. If there is a higher proportion of persons in a cluster for the customer data compared to the general population (e.g. 5% of persons are assigned to a cluster for the general population, but 15% of the customer data is closest to that cluster's centroid) then that suggests the people in that cluster to be a target audience for the company. On the other hand, the proportion of the data in a cluster being larger in the general population than the customer data (e.g. only 2% of customers closest to a population centroid that captures 6% of the data) suggests that group of persons to be outside of the target demographics.
Take a look at the following points in this step:
countplot() or barplot() function could be handy..inverse_transform() method of the PCA and StandardScaler objects to transform centroids back to the original data space and interpret the retrieved values directly.figure, axs = plt.subplots(nrows = 1, ncols = 2, figsize = (10,5))
figure.subplots_adjust(hspace = 1, wspace = .3)
sns.countplot(labels_customers, ax = axs[0])
axs[0].set_title('Customer Clusters')
sns.countplot(labels_azdias, ax = axs[1])
axs[1].set_title('General Clusters')
(Double-click this cell and replace this text with your own text, reporting findings and conclusions from the clustering analysis. Can we describe segments of the population that are relatively popular with the mail-order company, or relatively unpopular with the company?)
From the diagrams of comparison, it could be seen that cluster 2 is overpresented in the general public demographic data compared to the customers demographic data.
Congratulations on making it this far in the project! Before you finish, make sure to check through the entire notebook from top to bottom to make sure that your analysis follows a logical flow and all of your findings are documented in Discussion cells. Once you've checked over all of your work, you should export the notebook as an HTML document to submit for evaluation. You can do this from the menu, navigating to File -> Download as -> HTML (.html). You will submit both that document and this notebook for your project submission.